//
//  AnimeViewController.m
//  OtakuWorld
//
//  Created by iOS Two on 14-9-28.
//  Copyright (c) 2014年 iOS Two. All rights reserved.
//

#import "AnimeViewController.h"
#import "ImageViewController.h"
#import "UIImageView+MJWebCache.h"
#import "AnimeTableViewCell.h"
#import "ChineseString.h"
#import "pinyin.h"

@interface AnimeViewController ()

@end

@implementation AnimeViewController
-(void)viewWillAppear:(BOOL)animated {
    if (version >= 7) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"qwe_02"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    } else {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"qwe_02"] forBarMetrics:UIBarMetricsDefault];
    }
    [MobClick beginLogPageView:@"AnimeViewController"];

}
- (void)viewDidLoad {
    [super viewDidLoad];

    [self creatController];
    [self getData];
    // Do any additional setup after loading the view.
}

-(void)viewWillDisappear:(BOOL)animated {
    [MobClick endLogPageView:@"AnimeViewController"];
}
-(void)creatController {
    _maintable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kwidth, kHeight - 49 - 64) style:UITableViewStylePlain];
    _maintable.delegate = self;
    _maintable.dataSource = self;
    _maintable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_maintable];
    
    _search = [[UISearchBar alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
    _search.autocorrectionType = UITextAutocorrectionTypeNo;
    _search.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _search.keyboardType = UIKeyboardTypeDefault;
    _search.hidden = NO;
    _search.delegate = self;
    
    _search.placeholder = [NSString stringWithCString:"搜索"  encoding: NSUTF8StringEncoding];
    _maintable.tableHeaderView = _search;
//    [self setupRefresh];
    
    _searchDc = [[UISearchDisplayController alloc] initWithSearchBar:_search contentsController:self];
    _searchDc.searchResultsDataSource = self;
    _searchDc.searchResultsDelegate = self;
    _searchDc.delegate = self;
    [_searchDc setActive:NO];
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
    _searchImg = [[NSMutableArray alloc]init];
    _searchName  = [[NSMutableArray alloc]init];
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[cd]%@",searchText];
    _searchAuthors = [_nameArray filteredArrayUsingPredicate:resultPredicate];
    for (int i = 0; i<_searchAuthors.count; i++) {
        NSString *string =[_searchAuthors objectAtIndex:i];
        for (int j = 0; j<_nameArray.count; j++) {
            if ([string isEqualToString:[_nameArray objectAtIndex:j]]) {
                [_searchImg addObject:[_aidArray objectAtIndex:j]];
            }
        }
    }
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    [self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    return YES;
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:[[self.searchDisplayController.searchBar scopeButtonTitles]objectAtIndex:searchOption]];
    return YES;
}
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = YES;
    //準備搜尋前，把上面調整的TableView調整回全屏幕的狀態，如果要產生動畫效果，要另外執行animation代碼
    return YES;
}
-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    //搜尋結束後，恢復原狀，如果要產生動畫效果，要另外執行animation代碼
    return YES;
}
-(void)getData {
    [self showIndeterminateProgress];
    _aidArray = [[NSMutableArray alloc]init];
    _nameArray = [[NSMutableArray alloc]init];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc]initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://animemaster.sinaapp.com/api_album.php"]]];
    request.delegate = self;
    request.username = @"info";
    [request startSynchronous];
}
-(void)requestFinished:(ASIHTTPRequest *)request {
    SBJsonParser *jsonP = [[SBJsonParser alloc]init];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    if ([request.username isEqualToString:@"info"]) {
        NSArray *array =[jsonP objectWithData:[request responseData]];
        for (int i = 0; i < array.count; i++) {
            NSString *a;
            NSArray *b = [[[array objectAtIndex:i] objectForKey:@"desc"] componentsSeparatedByString:@","];
            if (b.count == 3) {
                a = [b objectAtIndex:2];
            } else if (b.count == 2) {
                a = [b objectAtIndex:1];
            } else if (b.count == 4){
                a = [b objectAtIndex:2];
            } else if (b.count == 1){
                a = [b objectAtIndex:0];
            } else if (b.count == 5){
                a = [b objectAtIndex:2];
            } else {
                a = [b objectAtIndex:0];
            }
            if ([[a substringWithRange:NSMakeRange(0, 1)] isEqualToString:@" "]) {
                a = [a substringFromIndex:1];
            }
            [_nameArray addObject:a];
            [dic setObject:[[array objectAtIndex:i] objectForKey:@"id"] forKey:a];
        }
        _nameArray = [self sortArray:_nameArray];
        for (int i = 0; i < _nameArray.count; i++) {
            [_aidArray addObject:[dic objectForKey:[_nameArray objectAtIndex:i]]];
        }
    }
    [HUD hide:YES];
}
-(void)requestFailed:(ASIHTTPRequest *)request {
    NSLog(@"请求失败");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 95;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]){
        return _searchAuthors.count;
    } else {
        return _nameArray.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AnimeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if(cell == nil) {
        cell = [[AnimeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    } else {
        for (UIView *view in [cell.contentView subviews]) {
            [view removeFromSuperview];
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]){
        cell.name.text = [_searchAuthors objectAtIndex:indexPath.row];
        
        [cell.image setImageURLStr:[NSString stringWithFormat:@"http://animemaster-meiupic.stor.sinaapp.com/data/cover/%@.jpg",[_searchImg objectAtIndex:indexPath.row]] placeholder:[UIImage imageNamed:@"2"]];
    } else {
        cell.name.text = [_nameArray objectAtIndex:indexPath.row];
        
        [cell.image setImageURLStr:[NSString stringWithFormat:@"http://animemaster-meiupic.stor.sinaapp.com/data/cover/%@.jpg",[_aidArray objectAtIndex:indexPath.row]] placeholder:[UIImage imageNamed:@"2"]];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ImageViewController *image = [[ImageViewController alloc]init];
    if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]){
        image.aid = [_searchImg objectAtIndex:indexPath.row];
        image.titleLabel = [_searchAuthors objectAtIndex:indexPath.row];
    } else {
        image.aid = [_aidArray objectAtIndex:indexPath.row];
        image.titleLabel = [_nameArray objectAtIndex:indexPath.row];
    }
    image.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:image animated:YES];
    [MobClick event:@"goToPic"];

}

-(NSMutableArray *)sortArray:(NSMutableArray *)array {
    NSMutableArray *chineseStringsArray = [NSMutableArray array];
    for(int i = 0;i < [array count];i++){
        ChineseString *chineseString = [[ChineseString alloc]init];
        chineseString.string = [NSString stringWithString:[array objectAtIndex:i]];
        if(chineseString.string == nil){
            chineseString.string = @"";
        }
        if(![chineseString.string isEqualToString:@""]){
            NSString *pinYinResult = [NSString string];
            for(int j = 0;j < chineseString.string.length;j++){
                NSString *singlePinyinLetter = [[NSString stringWithFormat:@"%c",pinyinFirstLetter([chineseString.string characterAtIndex:j])]uppercaseString];
                pinYinResult = [pinYinResult stringByAppendingString:singlePinyinLetter];
            }
            chineseString.pinYin = pinYinResult;
        }else{
            chineseString.pinYin = @"";
        }
        [chineseStringsArray addObject:chineseString];
    }
    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"pinYin" ascending:YES]];
    [chineseStringsArray sortUsingDescriptors:sortDescriptors];
    NSMutableArray *result=[NSMutableArray array];
    for(int i=0;i<[chineseStringsArray count];i++){
        [result addObject:((ChineseString*)[chineseStringsArray objectAtIndex:i]).string];
    }
    return result;
}
@end
